import request from '@/utils/request';
import { ResponseData, SUCCESS_CODE } from '@/utils/types.d';
import { ParkingOrderTableItem } from '../ParkingOrder/types.d';
import { CheckMergeResult, MergeRecordTableItem } from './types.d';

export async function queryMergeOrders(
  params: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: ParkingOrderTableItem[];
}> {
  if (!params?.plateNumber) {
    return { success: true, total: 0, data: [] };
  }
  const res: ResponseData<{
    total: number;
    list: ParkingOrderTableItem[];
  }> = await request('/api/merge-order/v1.0.0/merge-orders', {
    method: 'GET',
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.list };
  return { success: false, total: 0, data: [] };
}

export async function checkOrderMerge(orderNos: string[]) {
  if (!orderNos || orderNos.length < 2)
    return {
      success: false,
      message: '请选择两个及以上的订单',
      data: null,
    };
  const res: ResponseData<CheckMergeResult> = await request('/api/merge-order/v1.0.0/check-merge', {
    method: 'POST',
    data: { orderNos },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '核验成功', data: res.data };
  return { success: false, message: res?.message || '核验失败', data: null };
}

export async function cancelMerge(id: string) {
  if (!id) return { success: false, message: '' };
  const res = await request('/api/merge-order/v1.0.0/cancel', {
    method: 'DELETE',
    data: { id },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '取消成功' };
  return { success: false, message: res?.message || '取消失败' };
}

export async function confirmMerge(id: string, remark: string) {
  if (!id) return { success: false, message: '无法获取必要参数信息' };
  const res = await request('/api/merge-order/v1.0.0/confirm', {
    method: 'POST',
    data: { id, remark },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '确认成功' };
  return { success: false, message: res?.message || '确认失败' };
}

export async function queryMergeRecord(
  params: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: MergeRecordTableItem[];
}> {
  const res: ResponseData<{
    total: number;
    list: MergeRecordTableItem[];
  }> = await request('/api/merge-order/v1.0.0/list', {
    method: 'GET',
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.list };
  return { success: false, total: 0, data: [] };
}
